package com.exception;


import com.exception.BusinessException;
import com.exception.NotFoundException;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class PracticeExceptionHandler {

//    @ExceptionHandler(value = {Exception.class})
////    @ResponseBody
//    public String myError(Exception e, Model model){
//        model.addAttribute("msg",e);
//        System.out.println(e.getStackTrace());
//        return "error/myError";
//    }

    @ExceptionHandler(BusinessException.class)
    public ModelAndView businessExceptionHandler(HttpServletRequest request, BusinessException e){
        String errInfo = "业务异常：" + e.getErrInfo();
        System.out.println("业务会跑到这里来吗");
        ModelAndView mv = new ModelAndView();
        mv.addObject("title", errInfo);
        mv.addObject("url", request.getRequestURL().toString());
        mv.addObject("exception", e);
        mv.setViewName("error/MyError");
        return mv;
    }

    @ExceptionHandler(NotFoundException.class)
    public ModelAndView notFoundExceptionHandler(HttpServletRequest request,NotFoundException e){
        ModelAndView mv = new ModelAndView();
        System.out.println(e.getMessage());
        mv.addObject("title",e.getErrInfo());
        mv.addObject("url",request.getRequestURL().toString());
        mv.addObject("exception",e);
        mv.setViewName("error/MyError");
        return mv;
    }

    @ExceptionHandler(Exception.class)
    public ModelAndView exceptionHandler(HttpServletRequest request, Exception e) throws Exception {
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null){
            throw e;
            //有返回状态注解的异常，不在这里处理
        }
        System.out.println("这个呢");
        ModelAndView mv = new ModelAndView();
        mv.addObject("title", "非业务异常");
        mv.addObject("url", request.getRequestURL().toString());
        mv.addObject("exception", e);
        mv.setViewName("error/myError");
        return mv;
    }
}
